package com.example.blue;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.blue.ui.DynamicWaveFormView;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;

public class TuoCorActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener{
    private static final String TAG = "TuoCorActivity";
    private Button startButton;
    private String deviceId;
    private BluetoothService bluetoothService;
    private boolean isBound = false;
    private DynamicWaveFormView waveformViewX1;
    private DynamicWaveFormView waveformViewY1;
    private DynamicWaveFormView waveformViewZ1;
    private DynamicWaveFormView waveformViewX2;
    private DynamicWaveFormView waveformViewY2;
    private DynamicWaveFormView waveformViewZ2;
    private Spinner spinner;
    private Integer selectedSensorNum=0;
    private DataProcessorManager processorManager;
//    private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();
//    private ConcurrentLinkedQueue<byte[]> dataQueue2 = new ConcurrentLinkedQueue<>();
private LinkedBlockingDeque<byte[]> dataQueue = new LinkedBlockingDeque<>();
    private LinkedBlockingDeque<byte[]> dataQueue2 = new LinkedBlockingDeque<>();
    private Integer conDeviceNum=1;
    private String deviceMacLeft;
    private String deviceMacRight;
    private Integer handDir=0;
    private AlertDialog myDialog;
    private Button leftButton;
    private Button rightButton;
    private Boolean isLeftDeviceReceived=false;
    private Boolean isRightDeviceReceived=false;

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            if(conDeviceNum==1){
                if(handDir==1) {
                    dataQueue  = bluetoothService.getDataQueueLeft();
                    processorManager = DataProcessorManager.getInstance(dataQueue);
                }else{
                    dataQueue2  = bluetoothService.getDataQueueRight();
                    processorManager = DataProcessorManager.getInstance(dataQueue2);
                }
            } else{
                dataQueue  = bluetoothService.getDataQueueLeft();
                dataQueue2  = bluetoothService.getDataQueueRight();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CrashHandler.getInstance().init(this);
        setContentView(R.layout.activity_tuo_cor);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("陀螺仪校准");

        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        conDeviceNum = sp.getInt("conDeviceNum", 1);
        isLeftDeviceReceived=sp.getBoolean("isLeftDeviceReceived",false);
        isRightDeviceReceived=sp.getBoolean("isRightDeviceReceived",false);
        if(conDeviceNum==1) {

            handDir = sp.getInt("handDirection",0);
            if(handDir==1){
                if(isLeftDeviceReceived==false){
                    Toast.makeText(TuoCorActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                }
                deviceId = sp.getString("DEVICE_ADDRESS_LEFT", "");
            }else{
                if(isRightDeviceReceived==false){
                    Toast.makeText(TuoCorActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                }
                deviceId = sp.getString("DEVICE_ADDRESS_RIGHT", "");
            }

        }
        if(conDeviceNum==2){
            if(isLeftDeviceReceived==false){
                Toast.makeText(TuoCorActivity.this, "左手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
            }else if(isRightDeviceReceived==false){
                Toast.makeText(TuoCorActivity.this, "右手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
            }
            deviceMacLeft = sp.getString("DEVICE_ADDRESS_LEFT","");
            deviceMacRight=sp.getString("DEVICE_ADDRESS_RIGHT","");
            System.out.println("TuoCorActivity----deviceMacLeft:"+deviceMacLeft);
            System.out.println("TuoCorActivity----deviceMacRight:"+deviceMacRight);
            if (deviceMacLeft == null || deviceMacLeft.isEmpty() || deviceMacRight == null || deviceMacRight.isEmpty()) {
                Toast.makeText(TuoCorActivity.this, "未获取到蓝牙MAC地址，请重新连接", Toast.LENGTH_SHORT).show();
            }

        }

        spinner=findViewById(R.id.modeSpinner);
        String[] options = {"传感器1", "传感器2", "传感器3", "传感器4", "传感器5", "传感器6"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                options
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
// 监听选择
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selected = options[position];
                if(position!=selectedSensorNum){
                    waveformViewX1.clearDataPoints();
                    waveformViewY1.clearDataPoints();
                    waveformViewZ1.clearDataPoints();
                    waveformViewX2.clearDataPoints();
                    waveformViewY2.clearDataPoints();
                    waveformViewZ2.clearDataPoints();
                }
                selectedSensorNum=position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        waveformViewX1 = findViewById(R.id.waveformView1);
        waveformViewY1 = findViewById(R.id.waveformView2);
        waveformViewZ1 = findViewById(R.id.waveformView3);
        waveformViewX1.setYtitle("X轴加速度(m/s²)");
        waveformViewX1.setYRange(-20,20);
        waveformViewY1.setYtitle("Y轴加速度(m/s²)");
        waveformViewY1.setYRange(-20,20);
        waveformViewZ1.setYtitle("Z轴加速度(m/s²)");
        waveformViewZ1.setYRange(-20,20);

        waveformViewX2 = findViewById(R.id.waveformView4);
        waveformViewY2 = findViewById(R.id.waveformView5);
        waveformViewZ2 = findViewById(R.id.waveformView6);
        waveformViewX2.setYtitle("X轴角速度(deg/s)");
        waveformViewX2.setYRange(-500,500);
        waveformViewY2.setYtitle("Y轴角速度(deg/s)");
        waveformViewY2.setYRange(-500,500);
        waveformViewZ2.setYtitle("Z轴角速度(deg/s)");
        waveformViewZ2.setYRange(-500,500);

        View customView = LayoutInflater.from(this).inflate(R.layout.dialog_custom, null);
        myDialog = new AlertDialog.Builder(TuoCorActivity.this)
                .setView(customView)
                .create();
        leftButton=customView.findViewById(R.id.leftBtn);
        rightButton=customView.findViewById(R.id.rightBtn);
        leftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(TuoCorActivity.this, "开始校准", Toast.LENGTH_SHORT).show();
                processorManager = DataProcessorManager.getInstance(dataQueue);
                String mac = deviceMacLeft.replace(":", "");
                processorManager.setDeviceMac(mac);
                processorManager.temp=handDir;
                processorManager.setDataUpdateListener(TuoCorActivity.this);
                processorManager.startProcessing();
                processorManager.setProcessingFunction(ProcessingFunction.AccGyroBias);
                myDialog.dismiss();
            }
        });
        rightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(TuoCorActivity.this, "开始校准", Toast.LENGTH_SHORT).show();
                processorManager = DataProcessorManager.getInstance(dataQueue2);
                String mac = deviceMacRight.replace(":", "");
                processorManager.setDeviceMac(mac);
                processorManager.temp=handDir;
                processorManager.setDataUpdateListener(TuoCorActivity.this);
                processorManager.startProcessing();
                processorManager.setProcessingFunction(ProcessingFunction.AccGyroBias);
                myDialog.dismiss();
            }
        });

        startButton = findViewById(R.id.tuoCorrectBtn);
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(conDeviceNum==2){
                    if(isLeftDeviceReceived==false){
                        Toast.makeText(TuoCorActivity.this, "左手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                    }else if(isRightDeviceReceived==false){
                        Toast.makeText(TuoCorActivity.this, "右手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                    }else {
                        myDialog.show();
                    }
//                    AlertDialog.Builder builder = new AlertDialog.Builder(TuoCorActivity.this);
//                    builder.setTitle("请选择")
//                            .setItems(new String[]{"左手", "右手"}, (dialog, which) -> {
//                                if (which == 0) {
//                                    Toast.makeText(TuoCorActivity.this, "开始校准", Toast.LENGTH_SHORT).show();
//                                    processorManager = DataProcessorManager.getInstance(dataQueue);
//                                    String mac = deviceMacLeft.replace(":", "");
//                                    processorManager.setDeviceMac(mac);
//                                    processorManager.temp=handDir;
//                                    processorManager.setDataUpdateListener(TuoCorActivity.this);
//                                    processorManager.startProcessing();
//                                    processorManager.setProcessingFunction(ProcessingFunction.AccGyroBias);
//                                } else {
//                                    Toast.makeText(TuoCorActivity.this, "开始校准", Toast.LENGTH_SHORT).show();
//                                    processorManager = DataProcessorManager.getInstance(dataQueue2);
//                                    String mac = deviceMacRight.replace(":", "");
//                                    processorManager.setDeviceMac(mac);
//                                    processorManager.temp=handDir;
//                                    processorManager.setDataUpdateListener(TuoCorActivity.this);
//                                    processorManager.startProcessing();
//                                    processorManager.setProcessingFunction(ProcessingFunction.AccGyroBias);
//                                }
//                            })
//                            .setNegativeButton("取消", null)
//                            .show();
                }else {
                    if(handDir==1){
                        if(isLeftDeviceReceived==false){
                            Toast.makeText(TuoCorActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    if(handDir==2){
                        if (isRightDeviceReceived == false) {
                            Toast.makeText(TuoCorActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                        Toast.makeText(TuoCorActivity.this, "开始校准", Toast.LENGTH_SHORT).show();
                        //processorManager = DataProcessorManager.getInstance(dataQueue);
                        String mac = deviceId.replace(":", "");
                        System.out.println("TuoCorActivity----mac:" + mac);
                        processorManager.setDeviceMac(mac);
                        processorManager.setDataUpdateListener(TuoCorActivity.this);
                        processorManager.startProcessing();
                        processorManager.setProcessingFunction(ProcessingFunction.AccGyroBias);

                }
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(conDeviceNum==1) {
            if(handDir==1) {
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_LEFT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }else{
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }
        }
        if(conDeviceNum==2) {
            Intent intent = new Intent(this, BluetoothService.class);
            intent.putExtra("DEVICE_ADDRESS_LEFT", deviceMacLeft);
            intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceMacRight); // 如果需要
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }

    }
    @Override
    public void onDataProcessed(ProcessedData data) {
        String processedValue = data.getValue();
        String flag = data.getFlag();
        System.out.println("acccor-Flag:"+flag);
        System.out.println("acccor-Hex: " + processedValue);
        if(flag.equals("rawout")){
            String[] dataArr = processedValue.split(" ");   // 按逗号分割
            switch(selectedSensorNum){
                case 0:
                    String da1 = dataArr[0].length()>10?dataArr[0].substring(0,8):dataArr[0];
                    String da2 = dataArr[1].length()>10?dataArr[1].substring(0,8):dataArr[1];
                    String da3 = dataArr[2].length()>10?dataArr[2].substring(0,8):dataArr[2];
                    String da4 = dataArr[3].length()>10?dataArr[3].substring(0,8):dataArr[3];
                    String da5 = dataArr[4].length()>10?dataArr[4].substring(0,8):dataArr[4];
                    String da6 = dataArr[5].length()>10?dataArr[5].substring(0,8):dataArr[5];
                    waveformViewX1.addDataPoint(Float.parseFloat(da1));
                    waveformViewY1.addDataPoint(Float.parseFloat(da2));
                    waveformViewZ1.addDataPoint(Float.parseFloat(da3));
                    waveformViewX2.addDataPoint((Float.parseFloat(da4)/3.1415926f)*180);
                    waveformViewY2.addDataPoint((Float.parseFloat(da5)/3.1415926f)*180);
                    waveformViewZ2.addDataPoint((Float.parseFloat(da6)/3.1415926f)*180);
                    break;
                case 1:
                    String db1 = dataArr[9].length()>10?dataArr[9].substring(0,8):dataArr[9];
                    String db2 = dataArr[10].length()>10?dataArr[10].substring(0,8):dataArr[10];
                    String db3 = dataArr[11].length()>10?dataArr[11].substring(0,8):dataArr[11];
                    String db4 = dataArr[12].length()>10?dataArr[12].substring(0,8):dataArr[12];
                    String db5 = dataArr[13].length()>10?dataArr[13].substring(0,8):dataArr[14];
                    String db6 = dataArr[14].length()>10?dataArr[14].substring(0,8):dataArr[14];
                    waveformViewX1.addDataPoint(Float.parseFloat(db1));
                    waveformViewY1.addDataPoint(Float.parseFloat(db2));
                    waveformViewZ1.addDataPoint(Float.parseFloat(db3));
                    waveformViewX2.addDataPoint((Float.parseFloat(db4)/3.1415926f)*180);
                    waveformViewY2.addDataPoint((Float.parseFloat(db5)/3.1415926f)*180);
                    waveformViewZ2.addDataPoint((Float.parseFloat(db6)/3.1415926f)*180);
                    break;
                case 2:
                    String dc1 = dataArr[18].length()>10?dataArr[18].substring(0,8):dataArr[18];
                    String dc2 = dataArr[19].length()>10?dataArr[19].substring(0,8):dataArr[19];
                    String dc3 = dataArr[20].length()>10?dataArr[20].substring(0,8):dataArr[20];
                    String dc4 = dataArr[21].length()>10?dataArr[21].substring(0,8):dataArr[21];
                    String dc5 = dataArr[22].length()>10?dataArr[22].substring(0,8):dataArr[22];
                    String dc6 = dataArr[23].length()>10?dataArr[23].substring(0,8):dataArr[23];
                    waveformViewX1.addDataPoint(Float.parseFloat(dc1));
                    waveformViewY1.addDataPoint(Float.parseFloat(dc2));
                    waveformViewZ1.addDataPoint(Float.parseFloat(dc3));
                    waveformViewX2.addDataPoint((Float.parseFloat(dc4)/3.1415926f)*180);
                    waveformViewY2.addDataPoint((Float.parseFloat(dc5)/3.1415926f)*180);
                    waveformViewZ2.addDataPoint((Float.parseFloat(dc6)/3.1415926f)*180);
                    break;
                case 3:
                    String dd1 = dataArr[27].length()>10?dataArr[27].substring(0,8):dataArr[27];
                    String dd2 = dataArr[28].length()>10?dataArr[28].substring(0,8):dataArr[28];
                    String dd3 = dataArr[29].length()>10?dataArr[29].substring(0,8):dataArr[29];
                    String dd4 = dataArr[30].length()>10?dataArr[30].substring(0,8):dataArr[30];
                    String dd5 = dataArr[31].length()>10?dataArr[31].substring(0,8):dataArr[31];
                    String dd6 = dataArr[32].length()>10?dataArr[32].substring(0,8):dataArr[32];
                     waveformViewX1.addDataPoint(Float.parseFloat(dd1));
                    waveformViewY1.addDataPoint(Float.parseFloat(dd2));
                    waveformViewZ1.addDataPoint(Float.parseFloat(dd3));
                    waveformViewX2.addDataPoint((Float.parseFloat(dd4)/3.1415926f)*180);
                    waveformViewY2.addDataPoint((Float.parseFloat(dd5)/3.1415926f)*180);
                    waveformViewZ2.addDataPoint((Float.parseFloat(dd6)/3.1415926f)*180);
                    break;
                case 4:
                    String de1 = dataArr[36].length()>10?dataArr[36].substring(0,8):dataArr[36];
                    String de2 = dataArr[37].length()>10?dataArr[37].substring(0,8):dataArr[37];
                    String de3 = dataArr[38].length()>10?dataArr[38].substring(0,8):dataArr[38];
                    String de4 = dataArr[39].length()>10?dataArr[39].substring(0,8):dataArr[39];
                    String de5 = dataArr[40].length()>10?dataArr[40].substring(0,8):dataArr[40];
                    String de6 = dataArr[41].length()>10?dataArr[41].substring(0,8):dataArr[41];
                     waveformViewX1.addDataPoint(Float.parseFloat(de1));
                    waveformViewY1.addDataPoint(Float.parseFloat(de2));
                    waveformViewZ1.addDataPoint(Float.parseFloat(de3));
                    waveformViewX2.addDataPoint((Float.parseFloat(de4)/3.1415926f)*180);
                    waveformViewY2.addDataPoint((Float.parseFloat(de5)/3.1415926f)*180);
                    waveformViewZ2.addDataPoint((Float.parseFloat(de6)/3.1415926f)*180);
                    break;
                case 5:
                    String df1 = dataArr[45].length()>10?dataArr[45].substring(0,8):dataArr[45];
                    String df2 = dataArr[46].length()>10?dataArr[46].substring(0,8):dataArr[46];
                    String df3 = dataArr[47].length()>10?dataArr[47].substring(0,8):dataArr[47];
                    String df4 = dataArr[48].length()>10?dataArr[48].substring(0,8):dataArr[48];
                    String df5 = dataArr[49].length()>10?dataArr[49].substring(0,8):dataArr[49];
                    String df6 = dataArr[50].length()>10?dataArr[50].substring(0,8):dataArr[50];
                     waveformViewX1.addDataPoint(Float.parseFloat(df1));
                    waveformViewY1.addDataPoint(Float.parseFloat(df2));
                    waveformViewZ1.addDataPoint(Float.parseFloat(df3));
                    waveformViewX2.addDataPoint((Float.parseFloat(df4)/3.1415926f)*180);
                    waveformViewY2.addDataPoint((Float.parseFloat(df5)/3.1415926f)*180);
                    waveformViewZ2.addDataPoint((Float.parseFloat(df6)/3.1415926f)*180);
                    break;
            }

        }
        if(flag.equals("accgyrobias")){
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
//           String[] accres = processedValue.split("\n");
//            System.out.println("acccor"+accres[0]+" "+accres[1]+" "+accres[2]);
            Intent intent = new Intent(TuoCorActivity.this, TuoResActivity.class);
            intent.putExtra("accResult",processedValue);
            startActivity(intent);

        }
    }



    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        super.onStop();
        processorManager.setProcessingFunction(ProcessingFunction.Blank);
        processorManager.setzero();
        processorManager.stopProcessing();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        processorManager.setProcessingFunction(ProcessingFunction.Blank);
        processorManager.setzero();
        processorManager.stopProcessing();
    }
}